<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :inline="true" :model="queryForm" class="query-form">
        <el-form-item label="操作用户">
          <el-input v-model.trim="queryForm.username" style="width: 180px;" clearable placeholder="请输入操作用户" />
        </el-form-item>
        <el-form-item label="调用方法">
          <el-input v-model.trim="queryForm.func" style="width: 180px;" clearable placeholder="请输入调用方法" />
        </el-form-item>
        <el-form-item label="请求接口">
          <el-input v-model.trim="queryForm.requestUri" style="width: 180px;" clearable placeholder="请输入请求接口" />
        </el-form-item>
        <el-form-item label="IP地址">
          <el-input v-model.trim="queryForm.ip" style="width: 180px;" clearable placeholder="请输入IP地址" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryForm.status" placeholder="请选择状态" style="width: 180px;" clearable>
            <el-option label="成功" :value="1" />
            <el-option label="失败" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作时间">
          <el-date-picker v-model="queryForm.createTime" type="daterange" range-separator="-" start-placeholder="开始时间"
            end-placeholder="结束时间" value-format="YYYY-MM-DD" style="width: 220px;" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
          <el-button type="danger" @click="handleClear">清空</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="list" border stripe style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="操作用户" min-width="180" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.username || "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="func" label="调用方法" min-width="180" show-overflow-tooltip />
        <el-table-column prop="requestMethod" label="请求方式" width="100" show-overflow-tooltip />
        <el-table-column prop="content" label="接口描述" min-width="180" show-overflow-tooltip />
        <el-table-column prop="requestUri" label="请求接口" min-width="180" show-overflow-tooltip />
        <el-table-column prop="ip" label="IP地址" min-width="180" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 1" type="success">成功</el-tag>
            <el-tag v-else type="danger">失败</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="execTime" label="执行时间(ms)" width="120" />
        <el-table-column prop="createTime" label="操作时间" width="180">
          <template #default="scope">
            {{ $formatTimestamp(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleDetail(scope.row)">详情</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div style="height: 18px;"></div>

      <el-pagination v-model:current-page="queryForm.pageNum" v-model:page-size="queryForm.pageSize"
        :page-sizes="[10, 50, 100, 500, 1000]" :total="total" layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>

    <!-- 日志详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="日志详情" width="600px">
      <el-form label-width="100px">
        <el-form-item label="ID：">
          <span>{{ currentLog.id }}</span>
        </el-form-item>
        <el-form-item label="操作用户：">
          <span>{{ currentLog.username || "--" }}</span>
        </el-form-item>
        <el-form-item label="接口描述：">
          <span>{{ currentLog.content }}</span>
        </el-form-item>
        <el-form-item label="请求接口：">
          <span>{{ currentLog.requestUri }}</span>
        </el-form-item>
        <el-form-item label="请求方法：">
          <span>{{ currentLog.requestMethod }}</span>
        </el-form-item>
        <el-form-item label="IP地址：">
          <span>{{ currentLog.ip }}</span>
        </el-form-item>
        <el-form-item label="操作时间：">
          <span>{{ $formatTimestamp(currentLog.createTime) }}</span>
        </el-form-item>
        <el-form-item label="执行时间：">
          <span>{{ currentLog.execTime }} ms</span>
        </el-form-item>
        <el-form-item label="请求参数：">
          <el-input type="textarea" :rows="4" :value="currentLog.requestParams" readonly />
        </el-form-item>
        <el-form-item label="异常信息：">
          <el-input type="textarea" :rows="4" :value="currentLog.errorContent" readonly />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { apiLogList, apiLogDelete, apiLogClear } from '@/api/system/log'

// 查询表单
const queryForm = ref<Record<string, any>>({
  pageNum: 1,
  pageSize: 10
})

// 列表与分页
const list = ref<any[]>([])
const total = ref(0)

// 获取列表
const fetchList = async () => {
  const res = await apiLogList(queryForm.value)
  list.value = res.data?.records || []
  total.value = res.data?.totalRow || 0
}

// 对话框相关
const detailDialogVisible = ref(false)
const currentLog = ref<Record<string, any>>({})

// 查询
const handleQuery = () => {
  queryForm.value.pageNum = 1
  fetchList()
}

// 详情
const handleDetail = (row: any) => {
  currentLog.value = row
  detailDialogVisible.value = true
}

// 分页相关
const handleSizeChange = (val: number) => {
  queryForm.value.pageSize = val
  queryForm.value.pageNum = 1
  fetchList()
}

const handleCurrentChange = (val: number) => {
  queryForm.value.pageNum = val
  fetchList()
}

// 多选
const multipleSelection = ref<[]>([])
const handleSelectionChange = (val: any) => {
  multipleSelection.value = val
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确定要删除吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res = await apiLogDelete({ ids: String(row.id) })
    if (res.code == 200) {
      ElMessage.success('删除成功')
      handleQuery()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  })
}

// 批量删除
const handleBatchDelete = () => {
  if (multipleSelection.value.length == 0) {
    ElMessage.warning('请先选择要删除的数据')
    return
  }
  const ids = multipleSelection.value.map((item: any) => item.id).join(',')
  ElMessageBox.confirm(`确定要删除选中的数据吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res = await apiLogDelete({ ids: ids })
    if (res.code == 200) {
      ElMessage.success('删除成功')
      handleQuery()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  })
}

// 清空
const handleClear = () => {
  ElMessageBox.confirm(`确定要清空所有数据吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res = await apiLogClear({})
    if (res.code == 200) {
      ElMessage.success('清空成功')
      handleQuery()
    } else {
      ElMessage.error(res.message || '清空失败')
    }
  })
}

// 初始化
onMounted(() => {
  fetchList()
})
</script>

<style scoped>
.app-container {
  padding: 0px;
}

.query-form {
  margin-bottom: 0px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  text-align: right;
}
</style>